import aiohttp
import lxml.html
import json
import asyncio
import time
import random
from PIL import Image
from pyzbar import pyzbar
import io
import logging
logger = logging.getLogger("cmcc")
async def get_weixin(cardno, tel, amount, redis):
    jd_uids = await redis.hkeys("jd_cookie", encoding='utf-8')
    jd_id = random.choice(list(jd_uids))
    cookies = await redis.hget("jd_cookie", jd_id, encoding='utf-8')
    if not jd_uids:
        return {"code": "1", "message": "无可用京东账号"}
    # if amount == '200':
    #     url = 'https://jiayouka.jd.com/order/confirm?sku=200108054132'
    #     facePrice = "200"
    #     salePrice = "200.00"
    #     skuId = "200108054132"

    if amount == '200':
        url = 'https://jiayouka.jd.com/order/confirm?sku=200108001214'
        skuId = "200108001214"
    elif amount == '500':
        url = 'https://jiayouka.jd.com/order/confirm?sku=200107997830'
        skuId = "200107997830"
    elif amount == '1000':
        url = 'https://jiayouka.jd.com/order/confirm?sku=200107999423'
        skuId = "200107999423"
    elif amount == '2000':
        url = 'https://jiayouka.jd.com/order/confirm?sku=200108002419'
        skuId = "200108002419"
    else:
        return {"code": "1", "message": "不支持的面额"}


    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        "Cookie": cookies
    }
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get(url) as rsp:
            text = await rsp.text()
            root = lxml.html.fromstring(text)
            ele = root.xpath('//input[@name="repeatKey"]')
            if ele:
                repeat_key = ele[0].value
            else:
                logger.info(rsp.url)
                if "login" in str(rsp.url):
                    logger.info("京东账号%s重新登录", jd_id)
                    message = "登录失效"
                    # 删除失效账号
                    redis.hdel("jd_cookie", jd_id)
                else:
                    message = ""
                return {"code": "1", "message": message}

        price_url = 'https://jiayouka.jd.com/card/singleSkuInfoList'
        data = {
            "skuId": skuId
        }
        async with session.post(price_url, data=data) as rsp:
            price_data = await rsp.json()
            logger.info(price_data)
            if price_data['returnCode'] == '0':
                facePrice = str(price_data['respData'][0]['facePrice'])
                salePrice = price_data['respData'][0]['skuPrice']
                onlinePay = price_data['respData'][0]['promotionPrice'] or salePrice
                promoRfId = price_data['respData'][0]['promoRfId']
                promotionDiscount = price_data['respData'][0]['promotionDiscount']
            else:
                return {"code": "1", "message": price_data['returnMsg']}

        url = 'https://jiayouka.jd.com/order/createOrderSingleProduct'
        data = {"cardNum": cardno,
                "mailPhoneNo": tel,
                "facePrice": facePrice,
                "salePrice": salePrice,
                "skuId": skuId,
                "onlinePay": "%d" % float(onlinePay),
                "repeatKey": repeat_key,
                "payType": "1",
                "source": "6",
                "password": "",
                "jingdouPay": "0",
                "balancePay": "0",
                "jingquanPay": "0",
                "dongquanPay": "0",
                "dxqId": "",
                "promoRfId": promoRfId or "",
                "promotionDiscount": promotionDiscount or "0",
                "voiceCode": ""}

        # 下单
        logger.info(data)
        async with session.post(url, data=data) as rsp:
            data = await rsp.json()
            logger.info(data)
            pay_url = data['respData']
            if data['returnCode'] != '0':
                logger.info("京东账号%s|下单失败|%s", jd_id, data["returnMsg"])
                return {"code": "1", "message": data["returnMsg"]}
        fetch_data = {
            'url': pay_url,
            'js_script': 'function(){return globalVar;}',
            "headers": {
                "User-Agent": headers['User-Agent'],
                "Cookie": cookies,
            }
        }

        phantom_server = 'http://127.0.0.1:19900'
        n = 5
        weixin_data = ""
        orderId = ""
        pay_sign = ""

        # phantomjs 渲染页面
        while n > 0:
            async with session.post(phantom_server, data=json.dumps(fetch_data),
                                    headers={'Content-type': 'application/x-www-form-urlencoded'}) as rsp:
                data = await rsp.json()
                print(data['js_script_result'])
                if data['js_script_result'] and 'riskInfo' in data['js_script_result']:
                    root = lxml.html.fromstring(data['content'])
                    pay_sign = data['js_script_result']['paySign']
                    orderId = data['js_script_result']['orderId']
                    ele = root.xpath('//*[@id="weixin"]')
                    if ele:
                        channelSign = ele[0].attrib['channelsign']

                        weixin_data = {
                            'pageId': data['js_script_result']['pageId'],
                            'orderId': data['js_script_result']['orderId'],
                            'paySign': data['js_script_result']['paySign'],
                            'payingChannel': {"channelSign": channelSign},
                            'riskReqVo': data['js_script_result']['riskInfo'],
                        }
                        # print(weixin_data)
                    break
                else:
                    n -= 1

        if not data['js_script_result']:
            return {
                "pay_url": pay_url,
                "code": "8"
            }

        weixin_url = 'https://pcashier.jd.com/weixin/redirectWeixin?cashierId=1'
        weixin_data = {"bankPayRequestStr": json.dumps(weixin_data)}

        # 微信支付页面
        async with session.post(weixin_url, data=weixin_data, ) as rsp:
            url = rsp.url
            logger.info(url)
            if str(url) == 'https://pcashier.jd.com/success/fail':
                return {"code": '1', "message": "获取失败"}
        headers['Referer'] = str(url)
        headers['Host'] = 'pcashier.jd.com'
        headers['Origin'] = 'https://pcashier.jd.com'

        img_data = {
            'cashierId': '1',
            'orderId': orderId,
            'paySign': pay_sign
        }
        url = 'https://pcashier.jd.com/weixin/getWeixinImageUrl'
        # 页面二维码页面

        async with session.get(url, params=img_data, headers=headers) as rsp:
            img_rs = await rsp.read()

            img_rs = json.loads(img_rs.decode())
            print(img_rs)
            img_url = "https:" + img_rs['weixinImageUrl']

        # 获取图片
        async with session.get(img_url) as rsp:
            raw_data = await rsp.read()
            # print(raw_data)
            decode_result = pyzbar.decode(Image.open(io.BytesIO(raw_data)))
            wx_url = decode_result[0].data.decode()
            logger.info(wx_url)
            return {"code": "0", "wx_url": wx_url, "pay_url": pay_url, "orderId": orderId, "paySign": pay_sign, "jd_id": jd_id, "pay_amount": onlinePay}

async def youka_query(jd_id, order_id, redis):
    cookie = await redis.hget("jd_cookie", jd_id, encoding='utf-8')
    if not cookie:
        return {"orderstate": "9", "message": "登陆失效"}
    url = 'https://jiayouka.jd.com/order/detail/%s' % order_id
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        "Cookie": cookie
    }
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get(url) as rsp:
            text = await rsp.text()
            root = lxml.html.fromstring(text)
            ele = root.cssselect('.state-txt')
            message = ""
            if ele:
                message = ele[0].text
                if message == "充值成功":
                    orderstate = '0'
                elif message == '正在充值':
                    orderstate = '0'
                elif message == "等待付款":
                    orderstate = '8'
                elif message == '订单已取消':
                    orderstate = '1'
                else:
                    orderstate = '9'
            else:
                orderstate = '9'
                if "login" in str(rsp.url):
                    message = "登陆失效"

            return {"orderstate": orderstate, "message": message}


async def reget_wx(jd_id, order_id, pay_sign, redis, pay_url=None):

    cookie = await redis.hget("jd_cookie", jd_id, encoding='utf-8')
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        "Cookie": cookie
    }
    if not cookie:
        return {"code": "1", "message": "登陆失效"}
    async with aiohttp.ClientSession(headers=headers) as session:
        if pay_url:
            fetch_data = {
                'url': pay_url,
                'js_script': 'function(){return globalVar;}',
                "headers": {
                    "User-Agent": headers['User-Agent'],
                    "Cookie": cookie,
                }
            }
            phantom_server = 'http://127.0.0.1:19900'
            n = 5
            weixin_data = ""
            order_id = ""
            pay_sign = ""

            # phantomjs 渲染页面
            while n > 0:
                async with session.post(phantom_server, data=json.dumps(fetch_data),
                                        headers={'Content-type': 'application/x-www-form-urlencoded'}) as rsp:
                    data = await rsp.json()
                    print(data['js_script_result'])
                    if data['js_script_result'] and 'riskInfo' in data['js_script_result']:
                        root = lxml.html.fromstring(data['content'])
                        pay_sign = data['js_script_result']['paySign']
                        order_id = data['js_script_result']['orderId']
                        ele = root.xpath('//*[@id="weixin"]')
                        if ele:
                            channelSign = ele[0].attrib['channelsign']

                            weixin_data = {
                                'pageId': data['js_script_result']['pageId'],
                                'orderId': data['js_script_result']['orderId'],
                                'paySign': data['js_script_result']['paySign'],
                                'payingChannel': {"channelSign": channelSign},
                                'riskReqVo': data['js_script_result']['riskInfo'],
                            }
                            # print(weixin_data)
                        break
                    else:
                        n -= 1

                if not data['js_script_result']:
                    return {
                        "pay_url": pay_url,
                        "code": "8"
                    }

                weixin_url = 'https://pcashier.jd.com/weixin/redirectWeixin?cashierId=1'
                weixin_data = {"bankPayRequestStr": json.dumps(weixin_data)}

                # 微信支付页面
                async with session.post(weixin_url, data=weixin_data, ) as rsp:
                    url = rsp.url
                    logger.info(url)
                    if str(url) == 'https://pcashier.jd.com/success/fail':
                        return {"code": '1', "message": "获取失败"}
                headers['Referer'] = str(url)
                headers['Host'] = 'pcashier.jd.com'
                headers['Origin'] = 'https://pcashier.jd.com'
        img_data = {
            'cashierId': '1',
            'orderId': order_id,
            'paySign': pay_sign
        }
        url = 'https://pcashier.jd.com/weixin/getWeixinImageUrl'
        async with session.get(url, params=img_data, headers=headers) as rsp:
            img_rs = await rsp.read()
            img_rs = json.loads(img_rs.decode())
            logger.info(img_rs)
            if 'weixinImageUrl' in img_rs:
                img_url = "https:" + img_rs['weixinImageUrl']
            else:
                return {"code": '1', "message": ""}

        # 获取图片
        async with session.get(img_url) as rsp:
            raw_data = await rsp.read()
            decode_result = pyzbar.decode(Image.open(io.BytesIO(raw_data)))
            wx_url = decode_result[0].data.decode()
            return {"code": "0", "wx_url": wx_url, "jd_id": jd_id, "orderId": order_id, "paySign": pay_sign}


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    now = time.time()
    task = asyncio.ensure_future(get_weixin("1000114400008478430", "13888888889", "200"))
    loop.run_until_complete(task)
    print(time.time() - now)
    loop.close()
